package com.shuai.api_platform.utils;

import com.shuai.api_platform.common.ErrorCode;
import com.shuai.api_platform.exception.BusinessException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExcelReader {

    // 存储城市与城市编码对应关系的集合  city - adcode
    public static final Map<String, String> dataMap;

    static {
        ClassPathResource pathResource = new ClassPathResource("AMap_adcode_citycode.xlsx");
        int columnIndex1 = 0; // 第一列的索引（从0开始）
        int columnIndex2 = 1; // 第二列的索引（从0开始）

        try {
            dataMap = readExcelFile(pathResource.getInputStream(), columnIndex1, columnIndex2);
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "读取AMap_adcode_citycode.xlsx城市编码对应文件失败！");
        }
    }

    public static Map<String, String> readExcelFile(InputStream inputStream, int columnIndex1, int columnIndex2) {
        Map<String, String> dataMap = new HashMap<>();
        List<String> column1Data = new ArrayList<>();
        List<String> column2Data = new ArrayList<>();

        try (
                Workbook workbook = new XSSFWorkbook(inputStream)) {

            Sheet sheet = workbook.getSheetAt(0); // 假设数据在第一页

            for (Row row : sheet) {
                if (row.getRowNum() == 0) {
                    // 跳过标题行（如果有的话）  
                    continue;
                }

                Cell cell1 = row.getCell(columnIndex1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                Cell cell2 = row.getCell(columnIndex2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);

                if (cell1 != null && cell2 != null) {
                    String value1 = cell1.toString();
                    String value2 = cell2.toString();

                    column1Data.add(value1);
                    column2Data.add(value2);
                }
            }

            // 将两列数据组合为Map  
            for (int i = 0; i < column1Data.size(); i++) {
                dataMap.put(column1Data.get(i), column2Data.get(i));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return dataMap;
    }
}